{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(time-nowcasting)=\n",
    "# Introduction to Nowcasting\n",
    "\n",
    "Nowcasting is the prediction of economic indicators in the present, the very near future, and the very recent past—usually in a context where there is a lag in collecting and compiling information on that economic indicators and only partial information is available. For GDP, it can take over a year after the end of the so-called reference period for the final version of the data to be released. The two times you'll most often hear about nowcasting are in the context of the weather and GDP, two variables that people care deeply about!\n",
    "\n",
    "For most of this Chapter, we'll see an example of coding up a nowcast following an example based on Federal Reserve Board economist Chad Fulton's [notes](http://www.chadfulton.com/topics/statespace_large_dynamic_factor_models.html).\n",
    "\n",
    "Let's import the packages we'll need for this chapter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import types\n",
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "from statsmodels.graphics import tsaplots\n",
    "from rich import inspect\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "import matplotlib.dates as mdates\n",
    "import warnings\n",
    "\n",
    "# Plot settings\n",
    "plt.style.use(\n",
    "    \"https://github.com/aeturrell/coding-for-economists/raw/main/plot_style.txt\"\n",
    ")\n",
    "mpl.rcParams.update({\"lines.linewidth\": 1.2})\n",
    "# Set max rows displayed for readability\n",
    "pd.set_option(\"display.max_rows\", 8)\n",
    "\n",
    "# Set seed for random numbers\n",
    "seed_for_prng = 78557\n",
    "prng = np.random.default_rng(seed_for_prng)  # prng=probabilistic random number generator\n",
    "# Turn off warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nowcasting\n",
    "\n",
    "We need to begin with some definitions. A *reference period* is the time period of interest to the nowcast, ie the time period for which you would like to estimate a data point. The *data vintage* is the time when the data were issued, and this could be before or after the reference period—indeed, for data that are revised, it can be some time *after* the reference period. Finally, the *frequency* is how often reference periods occur. For nowcasting GDP, the frequency is typically quarterly.\n",
    "\n",
    "There are three parts to a typical nowcast:\n",
    "\n",
    "1. the forecast (the estimate of the data point shortly *before* the reference period)\n",
    "2. the nowcast (the estimate of the data point *during* the reference period)\n",
    "3. the backcast (the estimate of the data point *after* the reference period)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO remove input\n",
    "\n",
    "line_pos = [0, 3, 9, 12]\n",
    "colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n",
    "labels = [r\"$t-1$\", r\"$t$\", r\"$t+1 \\longrightarrow$\"]\n",
    "\n",
    "text_height_1 = 5\n",
    "text_height_2 = 2\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(5, 2))\n",
    "ax.set_xlim(line_pos[0], line_pos[-1])\n",
    "ax.set_ylim(line_pos[0], 6)\n",
    "ax.axvline(3, color=\"k\", linestyle=\":\")\n",
    "ax.axvline(9, color=\"k\", linestyle=\":\")\n",
    "ax.annotate(\"Forecast\", xy=(1.5, text_height_1), ha=\"center\")\n",
    "ax.annotate(\"True Nowcast\", xy=(6, text_height_1), ha=\"center\")\n",
    "ax.annotate(\"Backcast\", xy=(10.5, text_height_1), ha=\"center\")\n",
    "ax.annotate(\"Reference period\", xy=(6, text_height_2), ha=\"center\")\n",
    "ax.axvspan(xmin=line_pos[0], xmax=line_pos[1], facecolor=colors[0], alpha=0.3)\n",
    "ax.axvspan(xmin=line_pos[1], xmax=line_pos[2], facecolor=colors[1], alpha=0.3)\n",
    "ax.axvspan(xmin=line_pos[2], xmax=line_pos[3], facecolor=colors[2], alpha=0.3)\n",
    "ax.set_xticks(line_pos[1:])\n",
    "ax.set_xticklabels(labels)\n",
    "ax.set_yticklabels([])\n",
    "ax.set_yticks([])\n",
    "ax.set_xlabel(\"Time (reference period)\")\n",
    "ax.spines['right'].set_visible(True)\n",
    "ax.spines['top'].set_visible(True)\n",
    "ax.set_title(\"The different periods of a nowcast\", fontsize=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above figure, the model is the same for the three different sub-periods, the only difference is whether the target event has happened yet.\n",
    "\n",
    "Nowcasting is, in many ways, more complicated than forecasting. With forecasting, it's often the case that the *information set*, $\\Omega$, that you're using is fixed at a point in time (say, at time $t-1$), and you plug that information into a model, $f$, to try and predict your target variable, $y$, at $y_{t}$. With nowcasting, the problem becomes *dynamic*. We could be at $t-1$, $t$, or even $t+1$ (and anything inbetween) but we still want to use the *same* model to nowcast the value of $y$ at $t$! This is a tall order for any model; it has to cover input data that are changing over time. \n",
    "\n",
    "Nowcasts should be able to be constructed *whenever* new data are available; that is whenever the *information set*, $\\Omega$, is updated. And this could happen several times through the nowcasting period (in forecast, nowcast, or backcasting periods).\n",
    "\n",
    "Nowcasts have to deal with two particular challenges:\n",
    "\n",
    "- Nowcasts should be able to deal with mixed frequency data, so as to take information that is released between and within reference periods.\n",
    "- Nowcasts should be able to deal with \"ragged edges\" in the data; that is, different variables in the information set have different release frequencies so making a nowcast at any point in time will inevitably collect an information set that has some data missing.\n",
    "\n",
    "As a concrete example of the new data that arrive during the period of operation of a nowcast (and these two challenges), let's imagine we are trying to nowcast quarterly GDP but that every month there is a survey of growth expectations and every three weeks on a Monday there is a release on sales (which has some predictive power for GDP). And then let's imagine we are trying to take a nowcast."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO remove input\n",
    "\n",
    "time_min = \"30-11-2019\"\n",
    "periods = 50\n",
    "weekly_range = pd.date_range(\"01-01-2020\", freq=\"W\", periods=periods)\n",
    "months = mdates.MonthLocator(interval=1)\n",
    "months_fmt = mdates.DateFormatter('%b')\n",
    "\n",
    "weeks = mdates.WeekdayLocator(byweekday=mdates.MO)\n",
    "\n",
    "date_lines = [(weekly_range.min() - pd.DateOffset(months=1)).to_period(\"Q\"),\n",
    "              (weekly_range.min() + pd.DateOffset(months=1)).to_period(\"Q\"),\n",
    "              (weekly_range.min() + pd.DateOffset(months=5)).to_period(\"Q\"),\n",
    "              (weekly_range.min() + pd.DateOffset(months=8)).to_period(\"Q\")]\n",
    "\n",
    "locs_release_sales = pd.date_range(time_min, freq=\"W-MON\", periods=periods)\n",
    "locs_survey = pd.date_range(time_min, freq=\"M\", periods=periods)\n",
    "\n",
    "text_height = 7\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(7, 2))\n",
    "ax.set_xlim(weekly_range.min()-pd.DateOffset(months=1), weekly_range.max())\n",
    "ax.set_ylim(0, 8)\n",
    "for date_val in date_lines:\n",
    "    ax.axvline(date_val, color=\"k\", linestyle=\":\", alpha=0.3)\n",
    "annotations = [\"  Q1\", \"  Q2 (ref. period)\", \"  Q3\", \"  Q4\"]\n",
    "for i, tation in enumerate(annotations):\n",
    "    ax.annotate(tation, xy=(date_lines[i], text_height), ha=\"left\", fontsize=9)\n",
    "ax.annotate(\"  (Q1 GDP\\n  1st estimate released)\", xy=(date_lines[2], 6), ha=\"left\", va=\"center\", fontsize=7)\n",
    "ax.annotate(\"  (Q2 GDP 1st estimate released)\", xy=(date_lines[3], 6), ha=\"left\", va=\"center\", fontsize=7)\n",
    "for val in locs_release_sales[::3]:\n",
    "    ax.annotate(\"Sales Release\", xy=(val, 0), xytext=(val, 1), fontsize=6, rotation=90, ha=\"center\")\n",
    "for val in locs_survey:\n",
    "    ax.annotate(\"Survey\", xy=(val, 0), xytext=(val, 3), fontsize=6, rotation=90, ha=\"center\")\n",
    "ax.spines['right'].set_visible(False)\n",
    "ax.spines['top'].set_visible(False)\n",
    "ax.spines['left'].set_visible(False)\n",
    "ax.xaxis.set_major_locator(months)\n",
    "ax.xaxis.set_major_formatter(months_fmt)\n",
    "ax.xaxis.set_minor_locator(weeks)\n",
    "ax.yaxis.set_ticks([])\n",
    "ax.yaxis.set_ticklabels([])\n",
    "ax.tick_params(axis='x', which=\"minor\", bottom=True)\n",
    "ax.set_title(\"An example of high-frequency information releases relevant to a GDP nowcast\", fontsize=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above example we have three time series, all with different frequencies: the GDP 1st estimate releases (quarterly, but with a 1 quarter lag) and this we would use as an auto-regressive term in a model, the sales releases that come out every 3 weeks on a Monday, and the once-a-month survey releases. (In the diagram, the smaller tick marks denote every Monday.)\n",
    "\n",
    "A good nowcasting model needs to be able to incorporate all of the information in the example above, *and* be able to run at any point in time shown."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are a range of methods for nowcasting around, but the most popular broad classes are probably:\n",
    "\n",
    "- *bridge models*, which use timely indicators to forecast a target variable. They create a \"bridge\" between higher-frequency series and the target variables by regressing the target variables on the higher frequency indicators. They tend to produce iterated forecasts and the high-frequency series are likely to be aggregated to low frequency.\n",
    "- *MIDAS*, or mixed-data sampling regressions which use a multi-step forecast and weight high frequency indicators using a special type of polynomial of lags and include leads of the high-frequency indicators. There is not, typically, any time aggregation.\n",
    "- *dynamic factor models*, which suppose that a small number of unobserved “factors” can be used to explain a substantial portion of the variation and dynamics in a larger number of observed variables, and (most usefully for nowcasting) variables that are lower frequency can be estimated from the high-frequency indicators.\n",
    "\n",
    "For more on both MIDAS and Bridge Equation approaches, see {cite}`schumacher2016comparison`. For the rest of this chapter, we're going to look at the practical application in code of a dynamic factor model. The classic reference on dynamic factor models is"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dynamic Factor Model\n",
    "\n",
    "The equation below defines a dynamic factor model:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\vec{y}_t & = \\Lambda \\vec{f}_t + \\epsilon_t \\\\\n",
    "\\vec{f}_t & = A_1 \\vec{f}_{t-1} + \\dots + A_p \\vec{f}_{t-p} + u_t\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Here, $\\vec{y}_t$ is a vector of observed variables, $\\vec{f}_t$ is a vector of factors, $\\Lambda$ is a matrix of *factor loadings* (these are a map from factor space to the space of observed variables), and $\\epsilon_t \\thicksim \\mathcal{N}(0, \\Sigma_\\epsilon)$ and $u_t \\thicksim \\mathcal{N}(0, \\Sigma_u)$ with $\\Sigma_\\epsilon$ and $\\Sigma_u$ assumed to be diagonal matrices.\n",
    "\n",
    "The model above is specified in so-called *state space form*.\n",
    "\n",
    "As above the information set at vintage $v$ is $\\Omega_v$. The nowcast is given by \n",
    "\n",
    "$$\n",
    "\\mathbb{E\\left[y_t \\mid \\Omega_v \\right]}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data\n",
    "\n",
    "For our data, we'll use a US panel of economic data released at a monthly frequency, along with GDP, which is only released at a quarterly frequency in the US. The monthly datasets that we’ll be using come from FRED-MD database {cite}`mccracken2016fred`, and we will take real GDP from the companion FRED-QD database.\n",
    "\n",
    "The FRED-MD dataset was launched in January 2015, and vintages are available for each month since then. The FRED-QD dataset was fully launched in May 2018, and monthly vintages are available for each month since then. Our baseline exercise will use the February 2020 dataset (which includes data through reference month January 2020), and then we will examine how updated incoming data in the months of March - June influenced the model’s nowcast of real GDP growth in 2020Q2.\n",
    "\n",
    "#### Transformations\n",
    "\n",
    "Now, the data we download is not going to be stationary (for more on stationarity, see {ref}`time-series`). So we first need to transform it. Let's write a function that will do all of the transormations we need:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def transform(column, transforms):\n",
    "    \"\"\"Transforms a pandas series to make it stationary.\n",
    "\n",
    "    :param column: [description]\n",
    "    :type column: [type]\n",
    "    :param transforms: [description]\n",
    "    :type transforms: [type]\n",
    "    :return: [description]\n",
    "    :rtype: [type]\n",
    "    \"\"\"\n",
    "    transformation = transforms[column.name]\n",
    "    # For quarterly data like GDP, we will compute\n",
    "    # annualized percent changes\n",
    "    mult = 4 if column.index.freqstr[0] == 'Q' else 1\n",
    "    \n",
    "    # 1 => No transformation\n",
    "    if transformation == 1:\n",
    "        pass\n",
    "    # 2 => First difference\n",
    "    elif transformation == 2:\n",
    "        column = column.diff()\n",
    "    # 3 => Second difference\n",
    "    elif transformation == 3:\n",
    "        column = column.diff().diff()\n",
    "    # 4 => Log\n",
    "    elif transformation == 4:\n",
    "        column = np.log(column)\n",
    "    # 5 => Log first difference, multiplied by 100\n",
    "    #      (i.e. approximate percent change)\n",
    "    #      with optional multiplier for annualization\n",
    "    elif transformation == 5:\n",
    "        column = np.log(column).diff() * 100 * mult\n",
    "    # 6 => Log second difference, multiplied by 100\n",
    "    #      with optional multiplier for annualization\n",
    "    elif transformation == 6:\n",
    "        column = np.log(column).diff().diff() * 100 * mult\n",
    "    # 7 => Exact percent change, multiplied by 100\n",
    "    #      with optional annualization\n",
    "    elif transformation == 7:\n",
    "        column = ((column / column.shift(1))**mult - 1.0) * 100\n",
    "        \n",
    "    return column"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Outliers\n",
    "\n",
    "Following {cite}`mccracken2016fred`, we remove outliers (setting their value to missing). These are defined as observations that are more than 10 times the interquartile range from the series mean.\n",
    "\n",
    "However, in this exercise we are interested in nowcasting real GDP growth for 2020Q2, which was greatly affected by economic shutdowns stemming from the COVID-19 pandemic. During the first half of 2020, there are a number of series which include extreme observations, many of which would be excluded by this outlier test. Because these observations are likely to be informative about real GDP in 2020Q2, we only remove outliers for the period 1959-01 through 2019-12.\n",
    "\n",
    "The details of outlier removal are in the remove_outliers function, below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def remove_outliers(dta):\n",
    "    # Compute the mean and interquartile range\n",
    "    mean = dta.mean()\n",
    "    iqr = dta.quantile([0.25, 0.75]).diff().T.iloc[:, 1]\n",
    "    \n",
    "    # Replace entries that are more than 10 times the IQR\n",
    "    # away from the mean with NaN (denotes a missing entry)\n",
    "    mask = np.abs(dta) > mean + 10 * iqr\n",
    "    treated = dta.copy()\n",
    "    treated[mask] = np.nan\n",
    "\n",
    "    return treated"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Loading the data\n",
    "\n",
    "We will now write a function that can load the data for us. It's going to perform the following functions for both the FRED-MD and FRED-QD datasets:\n",
    "\n",
    "1. Based on the vintage argument, it downloads a particular vintage of these datasets from the base URL https://s3.amazonaws.com/files.fred.stlouisfed.org/fred-md into the `orig_[m|q]` variable.\n",
    "2. Extracts the column describing which transformation to apply into the `transform_[m|q]` (and, for the quarterly dataset, also extracts the column describing which factor an earlier paper assigned each variable to).\n",
    "3. Extracts the observation date (from the “sasdate” column) and uses it as the index of the dataset.\n",
    "4. Applies the transformations we need for stationarity.\n",
    "5. Removes outliers for the period 1959-01 through 2019-12.\n",
    "\n",
    "Here's the function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_fredmd_data(vintage):\n",
    "    \"\"\"Given a vintage, finds the FRED data and returns it.\n",
    "\n",
    "    :param vintage: The year month combo, eg \"2020-02\"\n",
    "    :type vintage: str\n",
    "    :return: all data associated with that vintage\n",
    "    :rtype: simple namespace\n",
    "    \"\"\"\n",
    "    base_url = \"https://files.stlouisfed.org/files/htdocs/fred-md\"\n",
    "    # - FRED-MD --------------------------------------------------------------\n",
    "    # 1. Download data\n",
    "    orig_m = (pd.read_csv(f'{base_url}/monthly/{vintage}.csv')\n",
    "                .dropna(how='all'))\n",
    "    \n",
    "    # 2. Extract transformation information\n",
    "    transform_m = orig_m.iloc[0, 1:]\n",
    "    orig_m = orig_m.iloc[1:]\n",
    "\n",
    "    # 3. Extract the date as an index\n",
    "    orig_m.index = pd.PeriodIndex(orig_m.sasdate.tolist(), freq='M')\n",
    "    orig_m.drop('sasdate', axis=1, inplace=True)\n",
    "\n",
    "    # 4. Apply the transformations\n",
    "    dta_m = orig_m.apply(transform, axis=0,\n",
    "                         transforms=transform_m)\n",
    "\n",
    "    # 5. Remove outliers (but not in 2020)\n",
    "    dta_m.loc[:'2019-12'] = remove_outliers(dta_m.loc[:'2019-12'])\n",
    "\n",
    "    # - FRED-QD --------------------------------------------------------------\n",
    "    # 1. Download data\n",
    "    orig_q = (pd.read_csv(f'{base_url}/quarterly/{vintage}.csv')\n",
    "                .dropna(how='all'))\n",
    "\n",
    "    # 2. Extract factors and transformation information\n",
    "    factors_q = orig_q.iloc[0, 1:]\n",
    "    transform_q = orig_q.iloc[1, 1:]\n",
    "    orig_q = orig_q.iloc[2:]\n",
    "\n",
    "    # 3. Extract the date as an index\n",
    "    orig_q.index = pd.PeriodIndex(orig_q.sasdate.tolist(), freq='Q')\n",
    "    orig_q.drop('sasdate', axis=1, inplace=True)\n",
    "\n",
    "    # 4. Apply the transformations\n",
    "    dta_q = orig_q.apply(transform, axis=0,\n",
    "                          transforms=transform_q)\n",
    "\n",
    "    # 5. Remove outliers (but not in 2020)\n",
    "    dta_q.loc[:'2019Q4'] = remove_outliers(dta_q.loc[:'2019Q4'])\n",
    "    \n",
    "    # - Output datasets ------------------------------------------------------\n",
    "    return types.SimpleNamespace(\n",
    "        orig_m=orig_m, orig_q=orig_q,\n",
    "        dta_m=dta_m, transform_m=transform_m,\n",
    "        dta_q=dta_q, transform_q=transform_q, factors_q=factors_q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's now grab the vintages we want and show some information about what we downloaded:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vintages = ['2020-02', '2020-03', '2020-04', '2020-05', '2020-06']\n",
    "dta = {date: load_fredmd_data(date) for date in vintages}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Print some information about the base dataset\n",
    "selected_vintage = \"2020-02\"\n",
    "n, k = dta[selected_vintage].dta_m.shape\n",
    "start = dta[selected_vintage].dta_m.index[0]\n",
    "end = dta[selected_vintage].dta_m.index[-1]\n",
    "\n",
    "print(f'For vintage {selected_vintage}, there are {k} series and {n} observations,'\n",
    "      f' over the period {start} to {end}.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see how the transformation and outlier removal works, here we plot three graphs of the RPI variable (“Real Personal Income”) over the period 2000-01 - 2020-01:\n",
    "\n",
    "1. The original dataset (which is in Billions of Chained 2012 Dollars)\n",
    "2. The transformed data (RPI had a transformation code of “5”, corresponding to log first difference)\n",
    "3. The transformed data, with outliers removed\n",
    "\n",
    "Notice that the large negative growth rate in January 2013 was deemed to be an outlier and so was replaced with a missing value (a NaN value).\n",
    "\n",
    "The [BEA release](https://www.bea.gov/news/2013/personal-income-and-outlays-january-2013) at the time noted that this was related to “the effect of special factors, which boosted employee contributions for government social insurance in January [2013] and which had boosted wages and salaries and personal dividends in December [2012].”."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(3, figsize=(14, 6))\n",
    "\n",
    "# Plot the raw data from the February 2020 vintage, for:\n",
    "vintage = '2020-02'\n",
    "variable = 'RPI'\n",
    "start = '2000-01'\n",
    "end = '2020-01'\n",
    "\n",
    "# 1. Plot the original dataset, for 2000-01 through 2020-01\n",
    "dta[vintage].orig_m.loc[start:end, variable].plot(ax=axes[0])\n",
    "axes[0].set(xlim=('2000','2020'), ylabel='Billons of $')\n",
    "axes[0].set_title('Original data', loc=\"center\")\n",
    "# 2. Plot the transformed data, still including outliers\n",
    "# (we only stored the transformation with outliers removed, so\n",
    "# here we'll manually perform the transformation)\n",
    "transformed = transform(dta[vintage].orig_m[variable],\n",
    "                        dta[vintage].transform_m)\n",
    "transformed.loc[start:end].plot(ax=axes[1])\n",
    "mean = transformed.mean()\n",
    "iqr = transformed.quantile([0.25, 0.75]).diff().iloc[1]\n",
    "axes[1].hlines([mean - 10 * iqr, mean + 10 * iqr],\n",
    "                transformed.index[0], transformed.index[-1],\n",
    "                linestyles='--', linewidth=1)\n",
    "axes[1].set(title='Transformed data, with bands showing outliers cutoffs',\n",
    "            xlim=('2000','2020'), ylim=(mean - 15 * iqr, mean + 15 * iqr),\n",
    "            ylabel='Percent')\n",
    "axes[1].annotate('Outlier', xy=('2013-01', transformed.loc['2013-01']),\n",
    "                    xytext=('2014-01', -5.3), textcoords='data',\n",
    "                    arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"),)\n",
    "\n",
    "# 3. Plot the transformed data, with outliers removed (see missing value for 2013-01)\n",
    "dta[vintage].dta_m.loc[start:end, 'RPI'].plot(ax=axes[2])\n",
    "axes[2].set(title='Transformed data, with outliers removed',\n",
    "            xlim=('2000','2020'), ylabel='Percent')\n",
    "axes[2].annotate('Missing value in place of outlier', xy=('2013-01', -1),\n",
    "                    xytext=('2014-01', -2), textcoords='data',\n",
    "                    arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3\"))\n",
    "\n",
    "fig.suptitle('Real Personal Income (RPI)')\n",
    "\n",
    "fig.tight_layout(rect=[0, 0.00, 1, 0.95]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Data definitions and details\n",
    "\n",
    "In addition to providing the raw data, {cite}`mccracken2016fred` and the FRED-MD/FRED-QD dataset provide additional information in appendices about the variables in each dataset:\n",
    "\n",
    "- FRED-MD Updated Appendix\n",
    "- FRED-QD Updated Appendix\n",
    "\n",
    "In particular, we’re interested in:\n",
    "\n",
    "- The human-readable description (e.g. the description of the variable “RPI” is “Real Personal Income”—*not* retail price index!)\n",
    "- The grouping of the variable (e.g. “RPI” is part of the “Output and income” group, while “FEDFUNDS” is in the “Interest and exchange rates” group).\n",
    "\n",
    "The descriptions make it easier to understand the results, while the variable groupings can be useful in specifying the factor block structure. For example, we may want to have one or more “Global” factors that load on all variables while at the same time having one or more group-specific factors that only load on variables in a particular group.\n",
    "\n",
    "The information from those appendices has been extracted into csvs that we can load in:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Definitions from the Appendix for FRED-MD variables\n",
    "# defn_m = pd.read_csv('https://github.com/aeturrell/coding-for-economists/blob/main/data/fred/FRED-MD_updated_appendix.csv')\n",
    "defn_m = pd.read_csv('data/fred/FRED-MD_updated_appendix.csv')\n",
    "defn_m.index = defn_m.fred\n",
    "\n",
    "# Definitions from the Appendix for FRED-QD variables\n",
    "# defn_q = pd.read_csv('https://github.com/aeturrell/coding-for-economists/blob/main/data/fred/FRED-QD_updated_appendix.csv')\n",
    "defn_q = pd.read_csv('data/fred/FRED-QD_updated_appendix.csv')\n",
    "defn_q.index = defn_q.fred\n",
    "\n",
    "# Example of the information in these files:\n",
    "defn_m.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "defn_q.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(defn_m[\"group\"].unique())\n",
    "print(defn_q[\"Group\"].unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "671f4d32165728098ed6607f79d86bfe6b725b450a30021a55936f1af379a247"
  },
  "kernelspec": {
   "display_name": "Python 3.8.6 64-bit ('codeforecon': conda)",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
